package com.medical.service.impl;
import com.hankcs.hanlp.HanLP;
import com.medical.mapper.ChatMessagesMapper;
import com.medical.model.param.Messages;
import com.medical.service.WordCloudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WordCloudServiceImpl implements WordCloudService {

    @Autowired
    private ChatMessagesMapper chatMessagesMapper;

    @Override
    public List<Map<String, Object>> analyzeKeywords() {
        // 获取所有聊天记录
        List<Messages> messages = chatMessagesMapper.getChatParameters("1");

        // 合并所有 content 内容
        StringBuilder allContent = new StringBuilder();
        for (Messages message : messages) {
            if (message.getContent() != null) {
                allContent.append(message.getContent()).append(" ");
            }
        }

        // 分词处理
        List<String> words = HanLP.segment(allContent.toString())
                .stream()
                .map(term -> term.word)
                .filter(word -> word.length() > 1 && isChinese(word)) // 过滤单字和非中文
                .collect(Collectors.toList());

        // 统计词频
        Map<String, Integer> frequencyMap = new HashMap<>();
        for (String word : words) {
            frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);
        }

        // 转换为 [{name: '单词', value: 5}, ...] 结构
        return frequencyMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(100)
                .map(entry -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", entry.getKey());
                    map.put("value", entry.getValue());
                    return map;
                })
                .collect(Collectors.toList());
    }

    // 判断是否是中文字符
    private boolean isChinese(String word) {
        for (char c : word.toCharArray()) {
            if (c >= 0x4E00 && c <= 0x9FA5) {
                return true;
            }
        }
        return false;
    }
}